package com.viknix.threadpool.manager.client.alertor;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.viknix.threadpool.manager.client.model.AlertorDTO;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Dongqi
 * @Date: 2021/11/7 14:52
 * @Version 1.0
 * @Description: 告警控制器
 */
public class AlertorHandler {

    private final Cache<String, Long> cache;

    public AlertorHandler(long alarmInterval) {
        cache = CacheBuilder.newBuilder()
                .expireAfterWrite(alarmInterval, TimeUnit.MINUTES)
                .build();
    }

    /**
     * 控制消息推送报警频率.
     *
     * @param alertorDTO
     * @return
     */
    public boolean isSend(AlertorDTO alertorDTO) {

        String identifier = alertorDTO.buildIdentifier();
        Long value = cache.getIfPresent(identifier);

        if (value == null) {
            cache.put(identifier, System.currentTimeMillis());
            return true;
        }
        return false;
    }
}
